/**
 * Copyright (C) 2011 GreenSoft S.A.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ar.com.greensoft.neosystem.model.constraint;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author Jorge E. Villaverde
 * @version 1.0.0
 * @date 04/07/2011  
 */
public class EuropeanArticleNumberValidator implements ConstraintValidator<EuropeanArticleNumber, String> {
	private int codeLenght;
	
	@Override
	public void initialize(EuropeanArticleNumber ean) {
		this.codeLenght = ean.value();
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if(value == null)
			return false;
		if(value.length() != codeLenght)
			return false;
		int checksum = ean13CheckSum(value);
		int vd = Integer.valueOf(value.substring(codeLenght-1, codeLenght));
		return (vd == checksum);
	}
	
	public static int ean13CheckSum(String ean13){
		int checksum = 0;
		for(int i = ean13.length()-1; i >= 1; i--){
			int digit = Integer.valueOf(ean13.substring(i-1,i));
			if(i % 2 != 0){
				checksum+=digit;
			}else{
				checksum+=(3*digit);
			}
		}
		return ((10 - (checksum % 10 )) % 10);
	}

}
